package com.dpiinc.TechPage.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.util.Log;
import android.view.KeyEvent;

import com.dpiinc.TechPage.AIWriteApplication;
import com.dpiinc.TechPage.AIWriteSettings;
import com.dpiinc.TechPage.AWLog;
import com.dpiinc.TechPage.LoginActivity;
import com.dpiinc.TechPage.R;
import com.dpiinc.TechPage.oss.FileDownloadHelper;
import com.dpiinc.TechPage.pen.dialog.PrivacyRightsDialog;

import com.dpiinc.TechPage.room.RoomAiWriterDatabase;
import com.dpiinc.TechPage.room.bean.UserEntity;
import com.dpiinc.TechPage.user.logic.RecognizeApiGetHelper;
import com.dpiinc.TechPage.utils.AudioRecordHelper;
import com.beiji.lib.pen.PenLog;
import com.beiji.lib.pen.PenManager;
import com.beiji.lib.pen.PenScanner;
import com.facebook.FacebookSdk;
import com.facebook.appevents.AppEventsLogger;
import com.mob.MobSDK;
import com.tencent.bugly.crashreport.CrashReport;


import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Locale;

/**
 * 闪屏界面
 */
public class LoadingActivity extends AppCompatActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //获取上一次配置语言，未配置为默认语言
        String app_language = getSharedPreferences("app_language", Context.MODE_PRIVATE).getString("lauType", Locale.getDefault().getLanguage());
        Resources resources = getResources();
        Configuration config = resources.getConfiguration();
        config.locale = new Locale(app_language, "");
        resources.updateConfiguration(config, resources.getDisplayMetrics());
        AIWriteApplication.Companion.instance().updateLanguage();

        setContentView(R.layout.activity_loading);

        boolean allow_privacy = getSharedPreferences("app_language", Context.MODE_PRIVATE).getBoolean("allow_privacy", false);
        if(allow_privacy){
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    jumpToPage();
                }
            }, 2500);
        }else{
            PrivacyRightsDialog.ShowDialog(LoadingActivity.this, new PrivacyRightsDialog.OnClickEditListener() {
                @Override
                public void onClickOK() {
                    getSharedPreferences("app_language",Context.MODE_PRIVATE).edit().putBoolean("allow_privacy",true).commit();
                    jumpToPage();
                }

                @Override
                public void onClickCancel() {
                    finish();
                }
            });
        }

    }

    /**
     * 获取MD5和SHA1值
     */
    private void getApplicationPackage() {

        try {
            PackageManager packageManager = AIWriteApplication.instance.getPackageManager();
            // 通过包管理器获取指定包名包含签名的信息
            @SuppressLint("PackageManagerGetSignatures") Signature signature = packageManager.getPackageInfo(this.getPackageName(), PackageManager.GET_SIGNATURES).signatures[0];


            MessageDigest messageDigestMd5 = MessageDigest.getInstance("MD5");
            MessageDigest messageDigestSHA1 = MessageDigest.getInstance("SHA1");

            // 通过 MessageDigest这个类来分别取出 Signature中存储的MD5和SHA1
            messageDigestMd5.update(signature.toByteArray());
            messageDigestSHA1.update(signature.toByteArray());

            // 把MessageDigest中存储的md5和sha1转为字符串
            String md5 = toHextring(messageDigestMd5.digest());
            String sha1 = toHextring(messageDigestSHA1.digest());
            Log.e("登录md5==============>" , md5 + ",,sha1===>" + sha1);
        } catch (PackageManager.NameNotFoundException | NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

    }

    private String toHextring(byte[] block) {

        StringBuffer buf = new StringBuffer();

        for (byte aBlock : block) {
            byte2Hex(aBlock, buf);
        }
        return buf.toString();
    }

    private void byte2Hex(byte b, StringBuffer buf) {
        char[] hexChars = {'0','1' ,'2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

        int high = ((b & 0xf0) >> 4);
        int low = (b & 0x0f);

        buf.append(hexChars[high]);
        buf.append(hexChars[low]);

    }


    @Override
    protected void onDestroy() {
        PrivacyRightsDialog.dismissDialog();
        super.onDestroy();
    }

    @SuppressLint("NewApi")
    private void jumpToPage() {
        AWLog.init(AIWriteApplication.Companion.isDebug());
        PenLog.init(AIWriteApplication.Companion.isDebug());
        AIWriteApplication.Companion.getInstance().updateLanguage();
        AIWriteSettings.INSTANCE.init(this);
        PenScanner.Companion.getInstance().init(AIWriteApplication.instance);
        PenManager.Companion.getInstance().init(AIWriteApplication.instance);
        AIWriteApplication.instance.getAiAdapter();
        CrashReport.initCrashReport(this, "14fc483d02", false);

        AudioRecordHelper.INSTANCE.init(AIWriteApplication.instance, AIWriteApplication.Companion.isDebug());
        FileDownloadHelper.INSTANCE.init(AIWriteApplication.instance);

        RecognizeApiGetHelper.recognizeApiGet();
        AIWriteApplication.instance.getOssConfig();

        FacebookSdk.sdkInitialize(getApplication());
        AppEventsLogger.activateApp(getApplication());

        MobSDK.init(this);
        MobSDK.submitPolicyGrantResult(true);

        if (!checkUserValid()) {
            startActivity(new Intent(this, LoginActivity.class));
        } else {
            startActivity(new Intent(this, BottomBarActivity.class));
        }
        finish();
    }

    private boolean checkUserValid() {
        RoomAiWriterDatabase db = RoomAiWriterDatabase.getInstance(this);
        List<UserEntity> list = db.userDao().getAll();
        return (list != null && list.size() > 0);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        /**
         * event.getRepeatCount() 重复次数,点后退键的时候，为了防止点得过快，触发两次后退事件，故做此设置。
         *
         * 建议保留这个判断，增强程序健壮性。
         */
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }
}
